package com.oriental.manage.core.utils;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.StaxDriver;
import com.thoughtworks.xstream.mapper.MapperWrapper;

/**
 * @author shulw
 * @version 1.0
 * @Desc:
 * @Date: 2016/11/11
 * @see:
 */
public class XstreamUtil {

    private XstreamUtil(){
    }

   // xstream.processAnnotations(XXX.class);


    /**
     * 将xml转换为bean
     *
     * @param <T> 泛型
     * @param xml 要转换为bean的xml
     * @param cls bean对应的Class
     * @return xml转换为bean
     */

    public static <T> T xmlToObject(String xml, Class<T> cls) {

       // XStream xstream = new XStream(new DomDriver());
        XStream xstream = new XStream() {
            //重写查找节点属性
            @Override
            protected MapperWrapper wrapMapper(MapperWrapper next) {
                return new MapperWrapper(next) {
                    @Override
                    public boolean shouldSerializeMember(Class definedIn, String fieldName) {
                        if (definedIn == Object.class) {
                            return false;
                        }
                        return super.shouldSerializeMember(definedIn, fieldName);
                    }
                };
            }
        };
        //xstream使用注解转换
        xstream.processAnnotations(cls);
        return (T) xstream.fromXML(xml);

    }

    /**
     * 将bean转换为xml
     *
     * @param obj 转换的bean
     * @return bean转换为xml
     */

    public static String objectToXml(Object obj) {

        XStream xStream = new XStream();
        xStream.autodetectAnnotations(true);
        //xstream使用注解转换
        xStream.processAnnotations(obj.getClass());
        return xStream.toXML(obj);

    }

    public static String toXml(Object object){
        XStream xStream = new XStream(new StaxDriver());
        xStream.processAnnotations(object.getClass());
        xStream.aliasSystemAttribute(null,"class");
        xStream.autodetectAnnotations(true);
        String xml = xStream.toXML(object);
        return formatXml(xml);
    }

    /**
     * xml转对象
     */
    public static <T> T toBean(String xml,Class<T> c){
        XStream xstream=new XStream(new DomDriver());
        xstream.processAnnotations(c);
        xstream.autodetectAnnotations(true);
        T obj=(T)xstream.fromXML(xml);
        return obj;
    }

    /**
     * 格式化xml xstream生成的xml没有头信息
     */
    private static String formatXml(String xml){
        try{
            return xml.replace("<?xml version=\"1.0\" ?>","<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        }catch(Exception e){
            return xml;
        }
    }

}
